<script lang="ts" setup>
  import { ref } from 'vue';
  import { CourseSearchParams } from '@/types/course';
  import ProvinceJSON from '@/config/province.json';
  import CityJSON from '@/config/city.json';

  const data = ref<CourseSearchParams>({});

  const emit = defineEmits(['submit']);

  const handleConfirm = () => {
    if (data.value.range) {
      [data.value.startDate, data.value.endDate] = data.value.range;
    }
    emit('submit', data.value);
  };

  const handleReset = () => {
    data.value = {};
    emit('submit', {});
  };

  const handleProvinceChanged = () => {
    data.value.city = undefined;
  };
</script>

<template>
  <a-form :model="data" layout="vertical">
    <a-row :gutter="12">
      <a-col :flex="1">
        <a-row :gutter="12">
          <a-col :span="6">
            <a-form-item hide-label field="name">
              <a-input v-model="data.name" allow-clear>
                <template #prefix>名称</template>
              </a-input>
            </a-form-item>
          </a-col>

          <a-col :span="6">
            <a-form-item hide-label field="province">
              <a-select
                v-model="data.province"
                allow-clear
                @change="handleProvinceChanged"
              >
                <template #prefix>省份</template>
                <a-option v-for="p in ProvinceJSON" :key="p.id" :value="p.id">
                  {{ p.name }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :span="6">
            <a-form-item hide-label field="city">
              <a-select v-model="data.city" allow-clear>
                <template #prefix>城市</template>
                <a-option
                  v-for="c in CityJSON[data.province as keyof typeof CityJSON]"
                  :key="c.id"
                  :value="c.id"
                >
                  {{ c.name }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :span="6"></a-col>

          <a-col :span="6">
            <a-form-item hide-label field="range">
              <a-range-picker
                v-model="data.range"
                allow-clear
                :placeholder="['入驻开始时间', '入驻结束时间']"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-col>
      <a-col flex="none" style="width: 80px">
        <a-row :gutter="[12, 12]">
          <a-col>
            <a-button type="primary" @click="handleConfirm"> 搜索 </a-button>
          </a-col>
          <a-col><a-button @click="handleReset">重置</a-button></a-col>
        </a-row>
      </a-col>
    </a-row>
  </a-form>
</template>
